package com.config;

import com.annotation.Aop;
import com.core.ProxyFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Description TODO
 * @Author 泥地里的蝴蝶
 * @Date 2024/5/10 20:56
 */
@Component
public class PointBeanPostProcess implements BeanPostProcessor {
    Map<String,Object> jointPointPathMap;
    Map<Class,Object> jointPointAnnotationMap;

    public PointBeanPostProcess(Map<String, Object> jointPointPathMap, Map<Class, Object> jointPointAnnotationMap) {
        this.jointPointPathMap = jointPointPathMap;
        this.jointPointAnnotationMap = jointPointAnnotationMap;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> beanClass = bean.getClass();
        String path = beanClass.getName();
        for (String s : jointPointPathMap.keySet()) {
            if (path.startsWith(s)){
                return ProxyFactory.tryBuild(bean,jointPointPathMap.get(s));
            }
        }
        for (Object aopObject : jointPointAnnotationMap.values()) {
            return ProxyFactory.tryBuild(bean,aopObject);
        }
        return bean;
    }

    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        Class<?> beanClass = bean.getClass();
        Aop aop = beanClass.getAnnotation(Aop.class);
        if(aop!=null){
            String jointPath = aop.jointPath();
            if(!jointPath.equals("")){
                jointPointPathMap.put(jointPath,bean);
            }else{
                jointPointAnnotationMap.put(aop.joinAnnotationClass(),bean);
            }
        }
        return bean;
    }
}
